package cn.avalon.org.service.impl;

import cn.avalon.basic.service.impl.BaseServiceImpl;
import cn.avalon.org.domain.Department;
import cn.avalon.org.mapper.DepartmentMapper;
import cn.avalon.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {

        List<Department> departments = departmentMapper.findAll();

        Map<Long, Department> map = new HashMap<>();

        for (Department department : departments) {
            map.put(department.getId(), department);
        }

        // 查询部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if (department.getParent_id() == null) {
                deptTree.add(department);
            } else {
                Long parent_id = department.getParent_id();
                Department parentDept = map.get(parent_id);
                parentDept.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
